package com.ys.web.ali;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.request.AlipaySystemOauthTokenRequest;
import com.alipay.api.request.AlipayUserInfoShareRequest;
import com.alipay.api.response.AlipaySystemOauthTokenResponse;
import com.alipay.api.response.AlipayUserInfoShareResponse;
import com.ys.base.BaseParam;
import com.ys.utils.alipay.AliPayHandler;
import com.ys.utils.alipay.model.MsgInfo;
import com.ys.utils.base.http.ResponseHandler;
import com.ys.utils.base.j2se.Common;
import com.ys.utils.base.j2se.DateHandler;
import com.ys.utils.base.j2se.Logger;
import com.ys.utils.base.j2se.StringHandler;
import com.ys.utils.redis.Redis;
import com.ys.utils.redis.key.UserKey;
import com.ys.utils.spring.config.SystemError;
import com.ys.utils.spring.properties.Config;
import com.ys.utils.spring.properties.SysConfig;
import com.ys.web.ali.manager.YsAlipayConfigManager;
import com.ys.web.user.info.UserInfoService;
import com.ys.web.user.login.LoginInfo;
import com.ys.web.user.login.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;

@RestController
@RequestMapping("/ali/user/")
public class AliUserAuthController {
    @Autowired
    private LoginService loginService;
    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private YsAlipayConfigManager ysAlipayConfigManager;

    @RequestMapping("authInfo")
    public String authInfo(){
        Map<String, String> keyValues = new HashMap<>();
        // 商户签约拿到的app_id，如：2013081700024223
        keyValues.put("app_id", StringHandler.getString(Config.pp.get("com.alipay.account.auth.appid"),"2021003187682122"));
        // 商户签约拿到的pid，如：2088102123816631
        keyValues.put("pid", StringHandler.getString(Config.pp.get("com.alipay.account.auth.pid"),"2088641003183392"));
        // 服务接口名称， 固定值
        keyValues.put("apiname", "com.alipay.account.auth");
        // 服务接口名称， 固定值
        keyValues.put("methodname", "alipay.open.auth.sdk.code.get");
        // 商户类型标识， 固定值
        keyValues.put("app_name", "mc");
        // 业务类型， 固定值
        keyValues.put("biz_type", "openservice");
        // 产品码， 固定值
        keyValues.put("product_id", "APP_FAST_LOGIN");
        // 授权范围， 固定值
        keyValues.put("scope", "kuaijie");
        // 商户唯一标识，如：kkkkk091125
        keyValues.put("target_id", BaseParam.getOrderSN());
        // 授权类型， 固定值
        keyValues.put("auth_type", "AUTHACCOUNT");
        // 签名类型
        keyValues.put("sign_type", "RSA2");
        try {
            if(Logger.isOnline()) {
                AliPayHandler aliPayHandler = new AliPayHandler(Config.pp);
                return ResponseHandler.success(aliPayHandler.sign(keyValues, ysAlipayConfigManager.ysAlipayConfig("2021003187682122").privateKey));
            }else{
                AliPayHandler aliPayHandler = new AliPayHandler("test",1);
                return ResponseHandler.success(aliPayHandler.sign(keyValues, "MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQCOJ7lT/M8BjQrxvph8mOnICLEpdFZENIpHu5z0rOVfga32WTz462dnSU7O4E5NkyXI9Eth9JT3maWILPaiOmxpgbRv1/M8FlRMwLp4Khw11fbiCdwe3H12IXa8O5wf33G69muvpYQYoujYc6HScPDHuEn0+LpuzzZzKvX8OJBrLcoH+W9x3e3H5MgLgJlhafkv5GmYXjUgnaIbON7fYoaeq9Ie6TFzyrhn6D0DNZbrKPKTKxL7HGnzM4D7z4wfcTpVZowlnBVVXJzJQ+iDGcaaZvJLUM5ktgMBztravzVgA2OMrugklTT3ewtveomNb3E8i4DVnqKGl7NxAqcLkGnbAgMBAAECggEAHfxDG3Q4NhuKM3QAtkeLCKbMt/HSQJDUmkz4zqOpvnucNlqcgeUl6qOL/BdUbQic78aYIBF3WsMOJ6tUWuP3+klhxjXHGOWc4pPEwZQgXzrC2Os7g0b/L+vfH9VzGUYIt2dDT8maE5hJhV7ew4UPRRGaiBHvQXB0C9cEDC/iRrkRDMwVp8f19edrI/LYeTYmW1lKyOoNn9w+Kd4B3IzVP1G+w5C1vjli5PW/SZgiT690L6/bukwmRdMUk1cDKfmQ1GPCeNM+Af7c3TRk44CdM2nIfvabj2gD3WllO5DVl5IRANsp+6FzB5TFfHng2Z1BwuAzcA2M26paDmqvRvBgAQKBgQDRyAbG/qsVG5cVkq1vN6HAjo7vXpHA/0Q/m5bdAxeQWaJklPec32sQNlIQ3pjAXKpXOw/cpMvTDONgbrCU3OuRspNmVHQRody5oKKCvCwMm5x3WcFPnSCCG0PIzxn8mCAG41feUm8jMNc4HXGkJvlashlewk4EaDn1ifaFX98diQKBgQCteXuAYN9VKDQyQu+s5yQUwCe79nMluXZ1WS9rcVqh5X/7Xc4mFK+i5BffHkDECpwqLMWq48xuRUA7GVnO8f11aiWv9E9Lmqsq72wGhQyHQQgvhbmrtI4JGKsFglkNXawXkgDpZhXMRn7XveX7jsrqGAoEJRMLk9y/OLzETql3QwKBgQDOJSLLz5ws/NTF5UI7BU8VGsHI5YSTRAU8AFgKzSwNtJdJAb4lUMMzxj10yFkQxr65Q5e9uc91kLernno1fraakQIZz6nTXdy6KOkpUWJz7UKfYfr9kilM0SAWJ7Wgq5jlS+if1x/RVABZ600uAwKMJnGZ1ZS27fjumWk//UsSCQKBgQCmLUV9iU7niIfXzf9CpnkN17U4fbF4Zd1wNGsUhZXImMyswwODvzUw2Ud02Mo6Ad/vFsyUE3v19ii9dF9vuqiOHYzUrTh4uEVX79qPtEx4FHf+7h8auO+HDzZlJKSiBSWhvp9Y9g3TjYRcrvDstbDz5utRZSKFaLOCCpvpgWEdeQKBgQCVea7SxcJ54v/u6zbrQlovlma2vlJBqGMS0Mkzaed9E1UPvXi1TDgOmdMBIp18ozop7KadWtfYZmBVv/d1ijHrL/qhmEySZ5TRULAX4Kbrk37NYDti55Z8jktVzwfyTZS/dpMpBN7MY+Si06yfiLO179v2FzS3xEuVHV6mKPHnpw=="));
            }
        } catch (AlipayApiException e) {
            Logger.error("500",e);
        }
        return ResponseHandler.error("500","系统繁忙,请稍后再试");
    }

    @RequestMapping("auth")
    public String auth(@RequestAttribute String uid,@RequestAttribute String ip, String auth_code,String userId){
        if(StringHandler.isEmpty(userId)){
            Logger.error("支付宝授权---用户id【"+uid+"】--支付宝id【"+userId+"】--ip【"+ip+"】:返回支付宝id为空，绑定失败");
            SystemError.wrapBs("500","授权失败...");
        }
        if (StringHandler.isNotEmpty(Config.pp.get("wallet.recharge.ali.black")) && Config.pp.get("wallet.recharge.ali.black").contains(userId)) {
            //冻结账户
            userInfoService.userWithdrawBlackInsert(StringHandler.getLong(uid),DateHandler.getLongFormatDate());
            // 修改提现记录状态
//                        userInfoService.withdrawRecordStatus(StringHandler.getLong(uid),7);
            Logger.error("支付宝授权----用户id:"+uid+"---支付宝id:"+userId+"---ip:"+ip+"--拉黑用户");
            //拉黑ip
            if(!Config.pp.get("sys.black.ips").contains(ip)) {
                Config.pp.put("sys.black.ips", Config.pp.get("sys.black.ips") + "," + ip);
                SysConfig.addBlackIp("," + ip);
            }
            Logger.error("支付宝授权---用户id【"+uid+"】--支付宝id【"+userId+"】--ip【"+ip+"】:已被拉黑，绑定失败");
            SystemError.wrapBs("500","系统异常");
        }
        Map<String,Object> map = new HashMap<>();
        AlipaySystemOauthTokenRequest request = new AlipaySystemOauthTokenRequest();
        request.setGrantType("authorization_code");
        request.setCode(auth_code);
        AlipaySystemOauthTokenResponse response = null;
        String appid = StringHandler.getString(Config.pp.get("com.alipay.account.auth.appid"),"2021003187682122");
        AliPayHandler aliPayHandler = null;
        try {
            if(Logger.isOnline()) {
                response = ysAlipayConfigManager.getDefaultAlipayClient(appid).certificateExecute(request);
            }else{
                aliPayHandler = new AliPayHandler("test",1);
                response = aliPayHandler.getDefaultAlipayClient(appid).certificateExecute(request);
            }
        } catch (AlipayApiException e) {
            Logger.error("支付宝授权",e);
        }
        if(Common.isNotEmpty(response) && response.isSuccess()){
            LoginInfo loginInfo = loginService.infoByUid(uid);
            AlipayUserInfoShareRequest request2 = new AlipayUserInfoShareRequest();
            try {
                AlipayUserInfoShareResponse response2 = ysAlipayConfigManager.getDefaultAlipayClient(appid).certificateExecute(request2, response.getAccessToken());
                if(Common.isNotEmpty(response2) && response2.isSuccess()){
                    loginInfo.setAlipayName(response2.getNickName());
                    loginInfo.setAlipayUid(userId);
                    int i = userInfoService.updateAliByUser(loginInfo);
                    if (i != 1) {
                        SystemError.wrapBs("500", "授权失败.");
                    }
                    Redis.key.del(UserKey.userInfoByUid(uid));
                    map.put("alipayName",loginInfo.alipayName);
                    map.put("alipayUid",loginInfo.alipayUid);
                    return ResponseHandler.success(map);
                } else {
                    return ResponseHandler.error("500","授权失败");
                }
            } catch (AlipayApiException e) {
                Logger.error("获取支付宝用户信息",e);
                SystemError.wrapBs("500","授权失败");
            }
        }
        return ResponseHandler.error("500","授权失败");
    }

    @RequestMapping("unBind")
    public String unBind(@RequestAttribute String uid){
        if (Boolean.parseBoolean(Config.pp.get("ys.ali.un.bind"))) {
            SystemError.wrapBs("500", "由于风控原因,解除绑定请联系在线客服");
        }
        LoginInfo loginInfo = loginService.infoByUid(uid);
        try {
            loginInfo.setAlipayName("");
            loginInfo.setAlipayUid("");
            int i = userInfoService.updateAliByUser(loginInfo);
            if (i != 1) {
                SystemError.wrapBs("500", "解绑失败");
            }
            Redis.key.del(UserKey.userInfoByUid(uid));
            return ResponseHandler.success();
        } catch (Exception e) {
            Logger.error("支付宝用户信息解绑",e);
            SystemError.wrapBs("500","解绑失败");
        }
        return ResponseHandler.error("500","解绑失败");
    }
    @RequestMapping("webPay")
    public String webPay(){
        AliPayHandler aliPayHandler = new AliPayHandler(Config.pp);
        try {
            Random random = new Random();
            int random_numner = random.nextInt(10);
            String total_amount = "0.1";
            if(random_numner>0)
                total_amount = StringHandler.getString((StringHandler.getFloat(random_numner,1)/100));
            JSONObject bizContent = aliPayHandler.bizContent(DateHandler.getLongFormatDate()+"",total_amount,"测试","","webPay","");
            MsgInfo msgInfo = aliPayHandler.webPay("2021003157650254",bizContent);
            return ResponseHandler.success(msgInfo.msg);
        } catch (AlipayApiException e) {
            Logger.error("webPay支付失败",e);
        }
        return ResponseHandler.error("500","支付失败");
    }

}
